package serova.valeriya.electricity;

import java.io.InputStreamReader;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class DataStore {
	
	private static final Logger LOGGER = Logger.getLogger(DataStore.class);
	
	private static DataStore dataStore;
	private List<String> fileContent;

	public static DataStore getCurrentInstance() {
		if (null == dataStore) {
			dataStore = new DataStore();
		} 
		return dataStore;
	}
	
	public DataStore() {
		init();
	}

	private void init() {
		Configuration configuration = Configuration.getCurrentInstance();
		if (null == configuration.getRegistrationDataPath()) {
			throw new IllegalStateException();
		}
		InputStreamReader stream = TariffDataSource.getInputStreamReader(configuration.getRegistrationDataPath());
		fileContent = TariffDataSource.getFileInformation(stream);					
	}
	
	public Input getCategoryAndLastRegistration() {
		Input result = new Input();
		result.setCategory(getCategoryFromFile());
		result.setPreviousRegistration(getPreviousRegistrationFromFile());
		return result;

	}

	private int getPreviousRegistrationFromFile() {
		String bill = fileContent.get(fileContent.size()-1);
		if (2 == fileContent.size()) {
			return Integer.valueOf(bill);
		} else {
			String[] array = AnalysisTariffData.getDataArray(bill);
			return getPreviousRegistration(array);
		}
	}
	
	private String getCategoryFromFile() {
		if(null == fileContent || fileContent.size() < 2){
			return StringUtils.EMPTY;
		}
		return fileContent.get(0);		
	}
	
	private static int getPreviousRegistration(String[] array) {
		if((null==array)||(0==array.length)){					
			return 0;	
		}	
		return  Integer.parseInt(array[1]);		
	}
	
	public boolean isAvailable() {
		return fileContent.size() > 1;
	}

}
